package com.demo.springcloud.netflix.erureka;

import java.text.MessageFormat;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import jakarta.annotation.PreDestroy;

/**
 * Spring Cloud Eureka Client A
 * 
 * @author xiaojianhx
 * @version V1.0.0 $ 2023-11-01 16:07:56 init ---- xiaojianhx
 */
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@RestController
public class SpringCloudNetflixEurekaConsumer {

    public static void main(String[] args) {
        SpringApplication.run(SpringCloudNetflixEurekaConsumer.class, args);
    }

    @PreDestroy
    public void destroy() {
        System.out.println("pre destroy running....");
    }

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private ProviderService providerService;

    @ResponseBody
    @RequestMapping("/main1")
    public String main() {

        var instance = loadBalancerClient.choose(ProviderConstants.SERVICE_ID);
        var url = "http://{0}:{1,number,#}/sub";
        url = MessageFormat.format(url, instance.getHost(), instance.getPort());
        return url + " --> " + restTemplate.getForObject(url, String.class);
    }

    @ResponseBody
    @RequestMapping("/main2")
    public String main2(String name) {
        return providerService.test(name);
    }
}